#include "qdriverfactory.h"

#include "driver/qabstractdriver.h"

QMap<QString,tagDriverInfo*> *QDriverFactory::m_meta_map;
QList<tagDriverInfo*>        *QDriverFactory::m_metas;


bool driverLessThan(tagDriverInfo* info1, tagDriverInfo *info2)
{
    return info1->m_show_index <info2->m_show_index;
}


QDriverFactory::QDriverFactory(const QString &name,
                               const QString &show_name,
                               const QString &show_group,
                               int            show_index,
                               const QMetaObject *driver)
{
    static bool s=false;
    if(!s)
    {
        m_meta_map=new QMap<QString,tagDriverInfo*>();
        m_metas=new QList<tagDriverInfo*>();
        s=true;
    }
    register_driver(name,show_name,show_group,show_index,driver);
}

void QDriverFactory::register_driver(const QString &name,
                                     const QString &show_name,
                                     const QString &show_group,
                                     int            show_index,
                                     const QMetaObject *driver)
{
    tagDriverInfo *info=m_meta_map->value(name);
    if(info==NULL)
    {
        info=new tagDriverInfo;
    }
    info->m_driver_object=driver;
    info->m_name=name;
    info->m_show_name=show_name;
    info->m_show_group=show_group;
    info->m_show_index=show_index;
    m_meta_map->insert(name,info);
    m_metas->append(info);
}

QAbstractDriver* QDriverFactory::create_driver(const QString &name)
{
    QAbstractDriver* driver=NULL;
    tagDriverInfo *info=m_meta_map->value(name);
    if(info==NULL)
    {
        return NULL;
    }
    const QMetaObject* obj=info->m_driver_object;

    if(obj!=NULL)
    {
        driver=(QAbstractDriver*)obj->newInstance();
        driver->init();
        driver->set_attribute(HOST_TYPE,name);
        driver->set_property_value("driver_type",info->m_show_group+"."+info->m_show_name);
    }

    return driver;
}

QList<tagDriverInfo*> QDriverFactory::get_driver_info()
{
    static bool s=false;
    if(!s)
    {
        sort();
        s=true;
    }
    return *m_metas;
}

tagDriverInfo* QDriverFactory::get_driver_info(const QString &name)
{
    return m_meta_map->value(name);
}

void QDriverFactory::sort()
{
    qStableSort(m_metas->begin(), m_metas->end(),driverLessThan);
}
